#include "ad_classmgrlist.h"
#include "ui_ad_classmgrlist.h"

#include <QModelIndex>

AD_ClassMgrList::AD_ClassMgrList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AD_ClassMgrList)
{
    ui->setupUi(this);

    model = new QSqlQueryModel();
    QString sql = R"(SELECT classes.class_id,
            userInfo.name,
            classes.class_name
       FROM classes
            JOIN
            userInfo  ON (userInfo.account = classes.consultant_id))";
    model->setQuery(sql);


    model->setHeaderData(0, Qt::Horizontal, tr("班级ID"));
    model->setHeaderData(1, Qt::Horizontal, tr("辅导员"));
    model->setHeaderData(2, Qt::Horizontal, tr("班级名"));

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->verticalHeader()->setHidden(true);

    ui->tableView->setModel(model);
}

AD_ClassMgrList::~AD_ClassMgrList()
{
    delete ui;
}

#include "ad_oneclassinfo.h"
void AD_ClassMgrList::on_pushButton_clicked()
{
    PAGEJUMP->setPage(DK_AD_OneClassInfo);
    auto wgt = qobject_cast<AD_OneClassInfo*>(PAGEJUMP->getPage(DK_AD_OneClassInfo));

    if(!wgt){
        return;
    }

    wgt->setMode("add");

}


void AD_ClassMgrList::on_pushButton_2_clicked()
{
    auto row = ui->tableView->currentIndex().row();
    int classId = model->data(model->index(row,0)).toInt();

    // student
    auto data = DB->getTableInfo("userInfo",QString("class_id = %1").arg(classId));
    if(data.isEmpty() == false){
        LOG("请先删除班级中全部学生");
        return ;
    }


    // courses
    auto cData = DB->getAllClassInfo(QString("classID = %1").arg(classId));

    if(cData.isEmpty() == false){
        LOG("请先删除班级与课程的全部关联");
        return ;
    }

    //获取选中的行
    int curRow = ui->tableView->currentIndex().row();

    //删除该行
    model->removeRow(curRow);

    // TODO
    update();
}


void AD_ClassMgrList::on_pushButton_3_clicked()
{
    auto wgt = qobject_cast<AD_OneClassInfo*>(PAGEJUMP->getPage(DK_AD_OneClassInfo));

    if(!wgt){
        return;
    }

    //获取选中的行
    int curRow = ui->tableView->currentIndex().row();
    if(curRow < 0 ){
        return;
    }
    PAGEJUMP->setPage(DK_AD_OneClassInfo);

    auto classID = ui->tableView->model()
            ->data(ui->tableView->model()->index(curRow,0)).toInt();

    wgt->setClassListComboBox(QString("class_id = %1").arg(classID));
    wgt->setMode("update");

}

void AD_ClassMgrList::update()
{
    QString sql = R"(SELECT classes.class_id,
            userInfo.name,
            classes.class_name
       FROM classes
            JOIN
            userInfo  ON (userInfo.account = classes.consultant_id))";
    model->setQuery(sql);
}

void AD_ClassMgrList::showEvent(QShowEvent *event)
{
    // TODO
    update();

}

